package com.shwread.android.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.shwread.android.qysw10000136.R;

import java.util.Arrays;
import java.util.List;


/**
 * 共用的列表dialog
 * @author 刘宾  
 * @date 2015年5月29日 上午10:20:44
 */
public class ArrayAlertDialog
        extends
        Dialog
        implements
        android.view.View.OnClickListener
{
	private int                 gravity;
	private Context             context;
	private ListView            lv;
	private TextView            cancel;
	private List<String>        data;
	private ItemClick			listener;
	
	/**
	 * 创建自定义dialog
	 * 
	 * @param context
	 */
	public ArrayAlertDialog(Context context) {
		this(context, Gravity.BOTTOM);
	}
	
	/**
	 * 创建自定义dialog
	 * 
	 * @param context
	 * @param gravity
	 *            布局文件的对齐方式
	 */
	public ArrayAlertDialog(Context context, int gravity) {
		super(context, R.style.no_title_dialog);
		this.context = context;
		this.gravity = gravity;
	}
	
	public void setData(String[] data){
		this.data = Arrays.asList(data);
	}
	public void setData(List<String> data){
		this.data = data;
	}
	public void setOnItemClickListener(ItemClick listener) {
		this.listener = listener;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View view = LayoutInflater.from(context).inflate(R.layout.custom_array_dialog, null);
		lv = (ListView) view.findViewById(R.id.custom_array_lv);
		cancel = (TextView) view.findViewById(R.id.custom_array_cancel);
		cancel.setOnClickListener(this);
		lv.setAdapter(new ArrayAdapter<String>(context, R.layout.custom_array_item, R.id.custom_array_item_name, data));
		if(null!=listener){
			lv.setOnItemClickListener(new OnItemClickListener()
			{
				@Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					listener.onItemClick(position);
					dismiss();
                }
			});
		}
		
		setContentView(view);
		getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		getWindow().setGravity(gravity);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.custom_array_cancel:
				this.dismiss();
				break;
		}
	}
	
	public interface ItemClick{
		void onItemClick(int itemPosition);
	}
}
